import { View } from '@tarojs/components';
import { Progress, Tag } from '@nutui/nutui-react-taro';
import { PlayStart, PlayStop } from '@nutui/icons-react-taro';
import { useState, useRef, useEffect } from 'react';
import { IVoice } from '../../..';
import Taro from '@tarojs/taro';
import './index.less';

interface IProps {
  voice: IVoice;
}

// 状态标签配置
const STATUS_CONFIG = {
  PROCESSING: {
    text: '处理中',
    type: 'primary'
  },
  CREATED: {
    text: '待处理',
    type: 'default'
  },
  COMPLETED: {
    text: '已完成',
    type: 'success'
  },
  FAILED: {
    text: '处理失败',
    type: 'danger'
  }
} as const;

export default function VoiceCard(props: IProps) {
  const { voice } = props;
  const [progress, setProgress] = useState<number>(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef<Taro.InnerAudioContext>();

  useEffect(() => {
    const audio = Taro.createInnerAudioContext();
    audio.src = voice.url;
    audioRef.current = audio;

    audio.onTimeUpdate(() => {
      setProgress((audio.currentTime / audio.duration) * 100);
    });
    
    audio.onEnded(() => {
      setIsPlaying(false);
      setProgress(0);
    });

    return () => {
      audio.destroy();
    };
  }, [voice.url]);

  const handleVoiceClick = () => {
    if (!audioRef.current) return;
    
    if (isPlaying) {
      audioRef.current.pause();
      setProgress(0);
    } else {
      audioRef.current.play();
    }
    setIsPlaying(!isPlaying);
  };

  return (
    <View className="voice-card">
      <View className="voice-info">
        <View className="voice-left">
          <View className="voice-title">{voice.name}</View>
          <Tag
            className="status-tag"
            type={STATUS_CONFIG[voice.status].type}
          >
            {STATUS_CONFIG[voice.status].text}
          </Tag>
        </View>
        <View 
          className="play-button"
          onClick={handleVoiceClick}
        >
          {isPlaying ? <PlayStop size={36} /> : <PlayStart size={36} />}
        </View>
      </View>
      {isPlaying && (
        <View className="progress-bar">
          <Progress 
            percent={progress}
            // strokeColor="var(--nutui-color-primary)"
            showText={false}
          />
        </View>
      )}
    </View>
  );
} 